<template>
  <div class="health-weekly-report-container">
    <!-- 页面标题 -->
    <div class="report-header">
      <h1>{{ headTitle }}</h1>
      <p class="report-date">{{ dateRange }}</p>
    </div>

    <!-- 返回按钮 -->
    <div class="float-button back-button" @click="goBack">
      <i class="el-icon-back"></i>
      <span>返回</span>
    </div>

    <!-- 本周概览 -->
    <div class="overview-section">
      <h2 class="section-title">本周概览</h2>
      <div class="overview-cards">
        <div class="overview-card">
          <div class="overview-icon">📊</div>
          <div class="overview-content">
            <h3>平均步数</h3>
            <p class="overview-value">{{ avgSteps }} 步</p>
            <p class="overview-subtitle">目标: {{ weeklyData.self && weeklyData.self.targetStep ? weeklyData.self.targetStep : '--' }} 步</p>
          </div>
        </div>

        <div class="overview-card">
          <div class="overview-icon">💧</div>
          <div class="overview-content">
            <h3>平均饮水量</h3>
            <p class="overview-value">{{ avgWater }} L</p>
            <p class="overview-subtitle">建议: 2.0 L/天</p>
          </div>
        </div>

        <div class="overview-card">
          <div class="overview-icon">🛌</div>
          <div class="overview-content">
            <h3>平均睡眠</h3>
            <p class="overview-value">{{ avgSleep }}</p>
            <p class="overview-subtitle">建议: 7-8小时/天</p>
          </div>
        </div>

        <div class="overview-card">
          <div class="overview-icon">🏃</div>
          <div class="overview-content">
            <h3>平均运动时长</h3>
            <p class="overview-value">{{ avgSport }} 小时</p>
            <p class="overview-subtitle">目标: {{ weeklyData.self && weeklyData.self.exerciseMinutesGoal ? weeklyData.self.exerciseMinutesGoal : '--' }} 小时/天</p>
          </div>
        </div>

        <div class="overview-card">
          <div class="overview-icon">❤️</div>
          <div class="overview-content">
            <h3>平均血压</h3>
            <p class="overview-value">{{ avgBloodPressure }}</p>
            <p class="overview-subtitle">正常范围: 120/80 mmHg</p>
          </div>
        </div>

        <div class="overview-card">
          <div class="overview-icon">⚖️</div>
          <div class="overview-content">
            <h3>体重变化</h3>
            <p class="overview-value">{{ weightChange }}</p>
            <p class="overview-subtitle">本周变化</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 趋势图表 -->
    <div class="trend-section">
      <h2 class="section-title">本周趋势</h2>
      <div class="trend-charts">
        <div class="chart-row">
          <div class="chart-card">
            <div ref="stepChart" class="chart"></div>
          </div>
          <div class="chart-card">
            <div ref="sleepChart" class="chart"></div>
          </div>
        </div>
        <div class="chart-row">
          <div class="chart-card">
            <div ref="waterChart" class="chart"></div>
          </div>
          <div class="chart-card">
            <div ref="weightChart" class="chart"></div>
          </div>
        </div>
        <div class="chart-row">
          <div class="chart-card">
            <div ref="systolicChart" class="chart"></div>
          </div>
          <div class="chart-card">
            <div ref="diastolicChart" class="chart"></div>
          </div>
        </div>
        <div class="chart-row">
          <div class="chart-card full-width">
            <div ref="sportChart" class="chart"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 每日数据汇总 -->
    <div class="daily-summary">
      <h2 class="section-title">每日数据</h2>
      <div class="days-grid">
        <div class="day-card" v-for="(day, date) in sortedDays" :key="date">
          <div class="day-header">
            <h3 class="day-title">{{ formatDate(date) }}</h3>
            <span class="day-week">{{ getDayOfWeek(date) }}</span>
          </div>
          <div class="day-content" v-if="day">
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-icon steps-icon">
                  <i class="el-icon-walk"></i>
                </div>
                <div class="metric-info">
                  <span class="metric-label">步数</span>
                  <span class="metric-value">{{ day.stepNumber || '--' }}</span>
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-icon sleep-icon">
                  <i class="el-icon-moon"></i>
                </div>
                <div class="metric-info">
                  <span class="metric-label">睡眠</span>
                  <span class="metric-value">{{ formatSleepTime(day.timeSubHour, day.timeSubMinutes) }}</span>
                </div>
              </div>
            </div>
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-icon water-icon">
                  <i class="el-icon-water-cup"></i>
                </div>
                <div class="metric-info">
                  <span class="metric-label">饮水</span>
                  <span class="metric-value">{{ day.waterVolume || '--' }} L</span>
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-icon sport-icon">
                  <i class="el-icon-time"></i>
                </div>
                <div class="metric-info">
                  <span class="metric-label">运动</span>
                  <span class="metric-value">{{ day.sportTimeLong || '--' }} 小时</span>
                </div>
              </div>
            </div>
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-icon blood-icon">
                  <i class="el-icon-first-aid-kit"></i>
                </div>
                <div class="metric-info">
                  <span class="metric-label">血压</span>
                  <span class="metric-value">{{ day.sbp ? `${day.sbp}/${day.dbp}` : '--' }}</span>
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-icon weight-icon">
                  <i class="el-icon-data-line"></i>
                </div>
                <div class="metric-info">
                  <span class="metric-label">体重</span>
                  <span class="metric-value">{{ day.weightDiff || '--' }} kg</span>
                </div>
              </div>
            </div>
          </div>
          <div class="day-content no-data" v-else>
            <div class="no-data-icon">
              <i class="el-icon-warning-outline"></i>
            </div>
            <p>这一天您并没有记录哦~</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 健康建议 -->
    <div class="advice-section">
      <h2 class="section-title">健康建议</h2>
      <div class="advice-cards">
        <div v-for="(suggestion, index) in weeklyData.suggestions" :key="index" class="advice-card" :class="getPriorityClass(suggestion.priority)">
          <div class="advice-header">
            <span class="advice-category">{{ suggestion.category }}</span>
            <span class="advice-title">{{ suggestion.title }}</span>
          </div>
          <div class="advice-content">
            <p v-for="(line, idx) in suggestion.content.split('\n')" :key="idx">{{ line }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部备注 -->
    <div class="report-footer">
      <p>数据统计周期: {{ getDateRange() }}</p>
      <p class="disclaimer">* 本报告仅供参考，如有健康问题请咨询专业医生</p>
    </div>

    <!-- 返回顶部按钮 -->
    <el-backtop :bottom="100">
      <div class="backtop">
        <i class="el-icon-caret-top"></i>
      </div>
    </el-backtop>
  </div>
</template>

<script>
import request from '@/utils/request.js'
import * as echarts from 'echarts'

export default {
  name: 'HealthWeeklyReport',
  props: {
    headTitle: {
      type: String,
      default: '个人健康周报'
    },
    weeklyData: {
      type: Object,
      default: () => ({
        avg_steps: null,
        avg_water: null,
        avg_sleep: null,
        steps_trend: null,
        water_trend: null,
        sleep_trend: null,
        start_date: null,
        end_date: null,
        days: {},
        advice: null
      })
    }
  },
  data() {
    return {
      currentWeekRange: '',
      encrypt: undefined,
      startDate: null,
      weeklyData: {
        days: {},
        self: {}
      },
      stepChart: null,
      sleepChart: null,
      waterChart: null,
      weightChart: null,
      systolicChart: null,
      diastolicChart: null,
      sportChart: null,
    }
  },
  computed: {
    avgSteps() {
      const steps = Object.values(this.weeklyData.days)
        .filter(day => day && day.stepNumber)
        .map(day => parseInt(day.stepNumber))
      return steps.length ? Math.round(steps.reduce((a, b) => a + b, 0) / steps.length) : '--'
    },
    avgWater() {
      const water = Object.values(this.weeklyData.days)
        .filter(day => day && day.waterVolume)
        .map(day => parseFloat(day.waterVolume))
      return water.length ? (water.reduce((a, b) => a + b, 0) / water.length).toFixed(2) : '--'
    },
    avgSleep() {
      const sleep = Object.values(this.weeklyData.days)
        .filter(day => day && day.timeSubHour)
        .map(day => {
          const hours = day.timeSubHour || 0
          const minutes = day.timeSubMinutes || 0
          return hours + minutes / 60
        })
      return sleep.length ? (sleep.reduce((a, b) => a + b, 0) / sleep.length).toFixed(1) + '小时' : '--'
    },
    avgSport() {
      const sport = Object.values(this.weeklyData.days)
        .filter(day => day && day.sportTimeLong)
        .map(day => parseFloat(day.sportTimeLong))
      return sport.length ? (sport.reduce((a, b) => a + b, 0) / sport.length).toFixed(1) : '--'
    },
    avgBloodPressure() {
      const pressures = Object.values(this.weeklyData.days)
        .filter(day => day && day.sbp && day.dbp)
      if (!pressures.length) return '--'
      
      const avgSbp = Math.round(pressures.reduce((sum, day) => sum + parseInt(day.sbp), 0) / pressures.length)
      const avgDbp = Math.round(pressures.reduce((sum, day) => sum + parseInt(day.dbp), 0) / pressures.length)
      return `${avgSbp}/${avgDbp}`
    },
    weightChange() {
      const weights = Object.values(this.weeklyData.days)
        .filter(day => day && day.weightDiff)
        .map(day => parseFloat(day.weightDiff))
      if (!weights.length) return '--'
      
      const firstWeight = weights[0]
      const lastWeight = weights[weights.length - 1]
      const change = lastWeight - firstWeight
      const sign = change > 0 ? '+' : ''
      return `${sign}${change.toFixed(1)} kg`
    },
    stepsTrend() {
      return this.calculateTrend('stepNumber')
    },
    waterTrend() {
      return this.calculateTrend('waterVolume')
    },
    sleepTrend() {
      return this.calculateTrend('timeSubHour')
    },
    dateRange() {
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      if (dates.length > 0) {
        const startDate = new Date(dates[0])
        const endDate = new Date(dates[dates.length - 1])
        const options = { month: 'long', day: 'numeric' }
        return `${startDate.toLocaleDateString('zh-CN', options)} - ${endDate.toLocaleDateString('zh-CN', options)}`
      }
      return '暂无数据'
    },
    sortedDays() {
      const days = { ...this.weeklyData.days }
      return Object.keys(days)
        .sort((a, b) => new Date(b) - new Date(a))
        .reduce((obj, key) => {
          obj[key] = days[key]
          return obj
        }, {})
    },
  },
  created() {
    this.encrypt = this.$route.query.encrypt
    this.startDate = this.$route.query.startDate
    this.currentWeekRange = this.getCurrentWeekRange()
    if (this.encrypt != null && this.encrypt != undefined) {
      this.WeeklyReportShow(this.encrypt)
    } else if (this.startDate) {
      this.getWeeklyReport(this.startDate)
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
    window.addEventListener('resize', this.resizeCharts)
  },
  watch: {
    'weeklyData.days': {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.$nextTick(() => {
            this.updateCharts()
          })
        }
      },
      deep: true
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
    this.disposeCharts()
  },
  methods: {
    initCharts() {
      this.stepChart = echarts.init(this.$refs.stepChart)
      this.sleepChart = echarts.init(this.$refs.sleepChart)
      this.waterChart = echarts.init(this.$refs.waterChart)
      this.weightChart = echarts.init(this.$refs.weightChart)
      this.systolicChart = echarts.init(this.$refs.systolicChart)
      this.diastolicChart = echarts.init(this.$refs.diastolicChart)
      this.sportChart = echarts.init(this.$refs.sportChart)
      this.updateCharts()
    },
    disposeCharts() {
      this.stepChart && this.stepChart.dispose()
      this.sleepChart && this.sleepChart.dispose()
      this.waterChart && this.waterChart.dispose()
      this.weightChart && this.weightChart.dispose()
      this.systolicChart && this.systolicChart.dispose()
      this.diastolicChart && this.diastolicChart.dispose()
      this.sportChart && this.sportChart.dispose()
    },
    resizeCharts() {
      this.stepChart && this.stepChart.resize()
      this.sleepChart && this.sleepChart.resize()
      this.waterChart && this.waterChart.resize()
      this.weightChart && this.weightChart.resize()
      this.systolicChart && this.systolicChart.resize()
      this.diastolicChart && this.diastolicChart.resize()
      this.sportChart && this.sportChart.resize()
    },
    updateCharts() {
      this.updateStepChart()
      this.updateSleepChart()
      this.updateWaterChart()
      this.updateWeightChart()
      this.updateSystolicChart()
      this.updateDiastolicChart()
      this.updateSportChart()
    },
    updateStepChart() {
      if (!this.stepChart) return
      
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      const data = dates.map(date => {
        const day = this.weeklyData.days[date]
        return day && day.stepNumber ? parseInt(day.stepNumber) : 0
      })

      const targetSteps = this.weeklyData.self?.targetStep || 10000

      const option = {
        title: {
          text: '每日步数趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c} 步',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: {
            color: '#606266'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        legend: {
          data: ['实际步数', '目标步数'],
          bottom: 0,
          textStyle: {
            color: '#909399'
          },
          itemWidth: 12,
          itemHeight: 12,
          icon: 'circle'
        },
        xAxis: {
          type: 'category',
          data: dates.map(date => this.formatDate(date)),
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#909399'
          },
          axisLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '步数',
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            color: '#909399'
          },
          axisLabel: {
            color: '#909399'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '实际步数',
            data: data,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#95B8F6'
            },
            lineStyle: {
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(149, 184, 246, 0.3)' },
                { offset: 1, color: 'rgba(149, 184, 246, 0.05)' }
              ])
            }
          },
          {
            name: '目标步数',
            data: new Array(dates.length).fill(targetSteps),
            type: 'line',
            symbol: 'none',
            lineStyle: {
              color: '#FFB6B9',
              type: 'dashed',
              width: 2
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      this.stepChart.setOption(option)
    },
    updateSleepChart() {
      if (!this.sleepChart) return
      
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      const data = dates.map(date => {
        const day = this.weeklyData.days[date]
        if (day && day.timeSubHour !== undefined) {
          const hours = day.timeSubHour || 0
          const minutes = day.timeSubMinutes || 0
          return hours + minutes / 60
        }
        return 0
      })

      // 计算有数据的天数的平均睡眠时长
      const validData = data.filter(value => value > 0)
      const avgSleep = validData.length > 0 
        ? (validData.reduce((a, b) => a + b, 0) / validData.length).toFixed(1)
        : 0

      const option = {
        title: {
          text: '每日睡眠时长趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const value = params[0].value
            const hours = Math.floor(value)
            const minutes = Math.round((value - hours) * 60)
            return `${params[0].name}<br/>睡眠时长: ${hours}小时${minutes}分钟`
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: {
            color: '#606266'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        legend: {
          data: ['实际睡眠', '平均睡眠'],
          bottom: 0,
          textStyle: {
            color: '#909399'
          },
          itemWidth: 12,
          itemHeight: 12,
          icon: 'circle'
        },
        xAxis: {
          type: 'category',
          data: dates.map(date => this.formatDate(date)),
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#909399'
          },
          axisLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '小时',
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            color: '#909399'
          },
          axisLabel: {
            color: '#909399',
            formatter: function(value) {
              return `${value}h`
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '实际睡眠',
            data: data,
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#B8C5E0' },
                { offset: 1, color: '#8B9DC3' }
              ]),
              borderRadius: [4, 4, 0, 0]
            }
          },
          {
            name: '平均睡眠',
            data: new Array(dates.length).fill(avgSleep),
            type: 'line',
            symbol: 'none',
            lineStyle: {
              color: '#FAA7AC',
              type: 'dashed',
              width: 2
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      this.sleepChart.setOption(option)
    },
    updateWaterChart() {
      if (!this.waterChart) return
      
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      const data = dates.map(date => {
        const day = this.weeklyData.days[date]
        return day && day.waterVolume ? parseFloat(day.waterVolume) : 0
      })

      const targetWater = 2.0

      const option = {
        title: {
          text: '每日饮水量趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c} L',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: {
            color: '#606266'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        legend: {
          data: ['实际饮水量', '目标饮水量'],
          bottom: 0,
          textStyle: {
            color: '#909399'
          },
          itemWidth: 12,
          itemHeight: 12,
          icon: 'circle'
        },
        xAxis: {
          type: 'category',
          data: dates.map(date => this.formatDate(date)),
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#909399'
          },
          axisLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '升(L)',
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            color: '#909399'
          },
          axisLabel: {
            color: '#909399'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '实际饮水量',
            data: data,
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#A8D8EA' },
                { offset: 1, color: '#7FB3D5' }
              ]),
              borderRadius: [4, 4, 0, 0]
            }
          },
          {
            name: '目标饮水量',
            data: new Array(dates.length).fill(targetWater),
            type: 'line',
            symbol: 'none',
            lineStyle: {
              color: '#FAA7AC',
              type: 'dashed',
              width: 2
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      this.waterChart.setOption(option)
    },
    updateWeightChart() {
      if (!this.weightChart) return
      
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      const data = dates.map(date => {
        const day = this.weeklyData.days[date]
        return day && day.weightDiff ? parseFloat(day.weightDiff) : null
      })

      const option = {
        title: {
          text: '每日体重趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const value = params[0].value
            if (value === null) return `${params[0].name}<br/>暂无数据`
            return `${params[0].name}<br/>体重: ${value} kg`
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: {
            color: '#606266'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        xAxis: {
          type: 'category',
          data: dates.map(date => this.formatDate(date)),
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#909399'
          },
          axisLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '体重(kg)',
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            color: '#909399'
          },
          axisLabel: {
            color: '#909399'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            data: data,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#FF9A8B'
            },
            lineStyle: {
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255, 154, 139, 0.3)' },
                { offset: 1, color: 'rgba(255, 154, 139, 0.05)' }
              ])
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      this.weightChart.setOption(option)
    },
    updateSystolicChart() {
      if (!this.systolicChart) return
      
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      const data = dates.map(date => {
        const day = this.weeklyData.days[date]
        return day && day.sbp ? parseInt(day.sbp) : 0
      })

      const option = {
        title: {
          text: '收缩压趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const value = params[0].value
            if (value === null) return `${params[0].name}<br/>暂无数据`
            return `${params[0].name}<br/>收缩压: ${value} mmHg`
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: {
            color: '#606266'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        xAxis: {
          type: 'category',
          data: dates.map(date => this.formatDate(date)),
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#909399'
          },
          axisLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: 'mmHg',
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            color: '#909399'
          },
          axisLabel: {
            color: '#909399'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            data: data,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#FF416C'
            },
            lineStyle: {
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255, 65, 108, 0.3)' },
                { offset: 1, color: 'rgba(255, 65, 108, 0.05)' }
              ])
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      this.systolicChart.setOption(option)
    },
    updateDiastolicChart() {
      if (!this.diastolicChart) return
      
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      const data = dates.map(date => {
        const day = this.weeklyData.days[date]
        return day && day.dbp ? parseInt(day.dbp) : 0
      })

      const option = {
        title: {
          text: '舒张压趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const value = params[0].value
            if (value === null) return `${params[0].name}<br/>暂无数据`
            return `${params[0].name}<br/>舒张压: ${value} mmHg`
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: {
            color: '#606266'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        xAxis: {
          type: 'category',
          data: dates.map(date => this.formatDate(date)),
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#909399'
          },
          axisLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: 'mmHg',
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            color: '#909399'
          },
          axisLabel: {
            color: '#909399'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            data: data,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#FF4B2B'
            },
            lineStyle: {
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255, 75, 43, 0.3)' },
                { offset: 1, color: 'rgba(255, 75, 43, 0.05)' }
              ])
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      this.diastolicChart.setOption(option)
    },
    updateSportChart() {
      if (!this.sportChart) return
      
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      const data = dates.map(date => {
        const day = this.weeklyData.days[date]
        return day && day.sportTimeLong ? parseFloat(day.sportTimeLong) : null
      })

      const targetMinutes = this.weeklyData.self?.exerciseMinutesGoal || 2

      const option = {
        title: {
          text: '每日运动时长趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const value = params[0].value
            if (value === null) return `${params[0].name}<br/>暂无数据`
            return `${params[0].name}<br/>运动时长: ${value} 小时`
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: {
            color: '#606266'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        legend: {
          data: ['实际运动时长', '目标运动时长'],
          bottom: 0,
          textStyle: {
            color: '#909399'
          },
          itemWidth: 12,
          itemHeight: 12,
          icon: 'circle'
        },
        xAxis: {
          type: 'category',
          data: dates.map(date => this.formatDate(date)),
          axisLabel: {
            interval: 0,
            rotate: 45,
            color: '#909399'
          },
          axisLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '小时',
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            color: '#909399'
          },
          axisLabel: {
            color: '#909399'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '实际运动时长',
            data: data,
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#11998e' },
                { offset: 1, color: '#38ef7d' }
              ]),
              borderRadius: [4, 4, 0, 0]
            }
          },
          {
            name: '目标运动时长',
            data: new Array(dates.length).fill(targetMinutes),
            type: 'line',
            symbol: 'none',
            lineStyle: {
              color: '#FAA7AC',
              type: 'dashed',
              width: 2
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      this.sportChart.setOption(option)
    },
    formatDate(dateStr) {
      const date = new Date(dateStr)
      return `${date.getMonth() + 1}月${date.getDate()}日`
    },
    formatSleepTime(hours, minutes) {
      if (!hours && !minutes) return '--'
      return `${hours}小时${minutes}分钟`
    },
    calculateTrend(field) {
      const values = Object.values(this.weeklyData.days)
        .filter(day => day && day[field])
        .map(day => parseFloat(day[field]))
      
      if (values.length < 2) return 0
      
      const firstValue = values[0]
      const lastValue = values[values.length - 1]
      return Math.round(((lastValue - firstValue) / firstValue) * 100)
    },
    getDateRange() {
      const dates = Object.keys(this.weeklyData.days || {}).sort()
      if (dates.length > 0) {
        const startDate = new Date(dates[0])
        const endDate = new Date(dates[dates.length - 1])
        const options = { month: 'long', day: 'numeric' }
        return `${startDate.toLocaleDateString('zh-CN', options)} - ${endDate.toLocaleDateString('zh-CN', options)}`
      }
      return '暂无数据'
    },
    WeeklyReportShow(encrypt) {
      request({
        url: `report/decryptWeek`,
        method: "get",
        params: {
          encrypt
        }
      }).then(res => {
        console.log('获取到的数据：', res.data)
        this.weeklyData = res.data
        this.$nextTick(() => {
          this.updateCharts()
        })
      })
    },
    getWeeklyReport(startDate) {
      request({
        url: 'report/userReport/Week',
        method: 'get',
        params: {
          zondDate: startDate
        }
      }).then(res => {
        if (res.data) {
          console.log('获取到的数据：', res.data)
          this.weeklyData = res.data
          this.$nextTick(() => {
            this.updateCharts()
          })
        }
      })
    },
    getCurrentWeekRange() {
      const now = new Date()
      const dayOfWeek = now.getDay() || 7 // 周日的day是0，我们转换为7
      const startDate = new Date(now)
      startDate.setDate(now.getDate() - dayOfWeek + 1)

      const endDate = new Date(now)
      endDate.setDate(now.getDate() + (7 - dayOfWeek))

      const options = { month: 'long', day: 'numeric' }
      return `${startDate.toLocaleDateString('zh-CN', options)} - ${endDate.toLocaleDateString('zh-CN', options)}`
    },
    getTrendIcon(trend) {
      if (!trend) return '➖'
      return trend > 0 ? '📈' : trend < 0 ? '📉' : '➖'
    },
    getTrendClass(trend) {
      if (!trend) return ''
      return trend > 0 ? 'positive' : trend < 0 ? 'negative' : ''
    },
    // 返回上一页
    goBack() {
      this.$router.go(-1)
    },
    getDayOfWeek(dateStr) {
      const date = new Date(dateStr)
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      return days[date.getDay()]
    },
    getPriorityClass(priority) {
      switch (priority) {
        case 1:
          return 'priority-high'
        case 2:
          return 'priority-medium'
        case 3:
          return 'priority-low'
        default:
          return ''
      }
    },
  }
}
</script>

<style scoped>
.health-weekly-report-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
  color: #606266;
  background-color: #f8f9fa;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.report-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.report-header h1 {
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 28px;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.report-date {
  color: #909399;
  font-size: 16px;
  font-weight: 300;
}

.section-title {
  color: #409EFF;
  border-bottom: 1px solid rgba(64, 158, 255, 0.1);
  padding-bottom: 10px;
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.overview-section {
  margin-bottom: 30px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.overview-card {
  flex: 1;
  min-width: 200px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.05);
  }
}

.overview-icon {
  font-size: 36px;
  margin-right: 20px;
  opacity: 0.8;
}

.overview-content h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #909399;
  font-weight: 400;
}

.overview-value {
  margin: 0;
  font-size: 28px;
  font-weight: 500;
  color: #2c3e50;
  letter-spacing: 0.5px;
}

.overview-subtitle {
  margin: 8px 0 0 0;
  font-size: 14px;
  color: #909399;
  font-weight: 300;
}

.advice-section {
  margin-bottom: 30px;
}

.advice-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.advice-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
}

.advice-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.05);
}

.advice-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.advice-category {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  margin-right: 10px;
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.advice-title {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.advice-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.advice-content p {
  margin: 8px 0;
}

.priority-high {
  border-left: 4px solid #F56C6C;
}

.priority-medium {
  border-left: 4px solid #E6A23C;
}

.priority-low {
  border-left: 4px solid #67C23A;
}

.report-footer {
  text-align: center;
  color: #909399;
  font-size: 13px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.disclaimer {
  font-style: italic;
  margin-top: 8px;
  font-weight: 300;
}

.float-button {
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 20px;
  background-color: white;
  border-radius: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 100;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  }
  
  i {
    font-size: 18px;
    color: #409EFF;
  }
  
  span {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
  }
}

.back-button {
  left: 20px;
  top: 20px;
}

.backtop {
  height: 100%;
  width: 100%;
  background-color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
  line-height: 40px;
  color: #409EFF;
  border-radius: 8px;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  }
}

.chart-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  height: 320px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
  margin-bottom: 20px;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.05);
  }
  
  .chart {
    width: 100%;
    height: 100%;
  }
}

.trend-charts {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-top: 24px;
}

.chart-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.chart-card.full-width {
  grid-column: 1 / -1;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-top: 20px;
}

.day-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.05);
  }
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.day-title {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.day-week {
  font-size: 14px;
  color: #909399;
  background: rgba(144, 147, 153, 0.1);
  padding: 6px 12px;
  border-radius: 6px;
  font-weight: 300;
}

.day-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.metric-row {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
}

.metric-row:last-child {
  margin-bottom: 0;
}

.metric-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(0, 0, 0, 0.02);
  padding: 8px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.metric-item:hover {
  background: rgba(0, 0, 0, 0.04);
  transform: translateY(-2px);
}

.metric-icon {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  
  i {
    font-size: 22px;
    color: white;
  }
}

.steps-icon {
  background: linear-gradient(135deg, #409EFF, #36D1DC);
}

.sleep-icon {
  background: linear-gradient(135deg, #8E2DE2, #4A00E0);
}

.water-icon {
  background: linear-gradient(135deg, #00B4DB, #0083B0);
}

.blood-icon {
  background: linear-gradient(135deg, #FF416C, #FF4B2B);
}

.weight-icon {
  background: linear-gradient(135deg, #11998e, #38ef7d);
}

.sport-icon {
  background: linear-gradient(135deg, #11998e, #38ef7d);
}

.metric-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.metric-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
  font-weight: 400;
}

.metric-value {
  font-size: 18px;
  color: #2c3e50;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.no-data {
  text-align: center;
  padding: 30px 0;
  
  .no-data-icon {
    font-size: 40px;
    color: #909399;
    margin-bottom: 12px;
    opacity: 0.5;
  }
  
  p {
    margin: 0;
    color: #909399;
    font-size: 14px;
    font-weight: 300;
  }
}

@media (max-width: 768px) {
  .chart-row {
    grid-template-columns: 1fr;
  }
  
  .overview-cards {
    grid-template-columns: 1fr;
  }
}
</style>